package com.dymall.trade.listener;

import com.dymall.api.po.Order;
import com.dymall.trade.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 支付状态监听器，用于监听消息队列传来的消息
 */
@Component
@RequiredArgsConstructor
public class PayStatusListener {
    private final OrderService orderService;
    //注解方式创建消息队列
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "trade.pay.success.queue", durable = "true"),
            exchange = @Exchange(value = "pay.topic", type = "topic"),
            key = {"pay.success"}
    ))
    public void paySuccessListener(Long orderId){
        //确保业务幂等性：方式一：给消息队列的消息加上唯一id；方式二：业务逻辑保证幂等性
        //1、查询订单
        Order order = orderService.getById(orderId);
        //2、判断订单状态，是否为未支付
        if(order == null || order.getStatus() != 1){
            //不处理
            return;
        }
        //3、标记订单状态为已支付
        orderService.markOrderPaySuccess(orderId);
    }
}
